package net.sapfree.core.util;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class POP3Util
{

    public POP3Util()
    {
    }
    
    private static String saveAttachPath = "D:\\temp";
    private static String dateformat = "yy-MM-dd HH:mm";
    private static int p = 0;

    public static void main(String args[])
    {
        try
        {
            String popServer = "pop3.163.com";
            String popUser = "coverstory";
            String popPassWord = "123654789";
            allmailList(popServer, popUser, popPassWord, "D:\\temp", null);
        }
        catch(Exception ex)
        {
            System.out.println("Usage: java com.lotontech.mail.POPMail popServer popUser popPassword");
        }
    }

    public static List allmailList(String popServer, String popUser, String popPassword, String path, Map map)
        throws Exception
    {
        Store store;
        Folder folder;
        List list;
        store = null;
        folder = null;
        list = new ArrayList();
        String URL = "";
        try
        {
            java.util.Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props, null);
            store = session.getStore("pop3");
            store.connect(popServer, popUser, popPassword);
            folder = store.getDefaultFolder();
            if(folder == null)
                throw new Exception("\u6CA1\u6709\u6587\u4EF6\u5939\uFF01");
            folder = folder.getFolder("INBOX");
            if(folder == null)
                throw new Exception("\u6CA1\u6709POP3\u6536\u4EF6\u7BB1");
            folder.open(1);
            Message msgs[] = folder.getMessages();
            for(int msgNum = 0; msgNum < msgs.length; msgNum++)
                try
                {
                    StringBuffer bodytext = new StringBuffer();
                    String mailid = ((MimeMessage)msgs[msgNum]).getMessageID();
                    if(map == null)
                    {
                        int mailNum = ((MimeMessage)msgs[msgNum]).getMessageNumber();
                        String sjr = getMailAddress("to", (MimeMessage)msgs[msgNum]);
                        String from = ((InternetAddress)((MimeMessage)msgs[msgNum]).getFrom()[0]).getAddress();
                        if(from == null)
                            from = "";
                        String personal = ((InternetAddress)((MimeMessage)msgs[msgNum]).getFrom()[0]).getPersonal();
                        if(personal == null)
                            personal = "";
                        String fromaddr = (new StringBuilder(String.valueOf(personal))).append("\u0448").append("<").append(from).append(">").toString();
                        String subject = ((MimeMessage)msgs[msgNum]).getSubject();
                        String chaos = getMailAddress("BCC", (MimeMessage)msgs[msgNum]);
                        String date = getSentDate((MimeMessage)msgs[msgNum]);
                        boolean fujian = isContainAttach((MimeMessage)msgs[msgNum]);
                        boolean hz = getReplySign((MimeMessage)msgs[msgNum]);
                        String attachname = AttachMentName((MimeMessage)msgs[msgNum], null);
                        getMailContent((MimeMessage)msgs[msgNum], bodytext);
                        String neitongtxt = getBodyText("txt", bodytext);
                        String neitonghtml = getBodyText("html", bodytext);
                        boolean attachresult = false;
                        URL = setFinallyPath(path, mailid, date);
                        if(fujian)
                        {
                            setAttachPath(URL);
                            attachresult = saveAttachMent((MimeMessage)msgs[msgNum]);
                        }
                        MailVO vo = new MailVO();
                        vo.setMailid(mailid);
                        vo.setMailNum(mailNum);
                        vo.setTo(sjr);
                        vo.setFrom(fromaddr);
                        vo.setSubject(subject);
                        vo.setChaosong(chaos);
                        vo.setDate(date);
                        vo.setAccessory(fujian);
                        vo.setHuizhi(hz);
                        vo.setAttachname(attachname);
                        vo.setContenttxt(neitongtxt);
                        vo.setContenthtml(neitonghtml);
                        vo.setAttachresult(attachresult);
                        vo.setAttachurl(URL);
                        list.add(vo);
                    } else
                    if(!map.containsKey(mailid))
                    {
                        int mailNum = ((MimeMessage)msgs[msgNum]).getMessageNumber();
                        String sjr = getMailAddress("to", (MimeMessage)msgs[msgNum]);
                        String from = ((InternetAddress)((MimeMessage)msgs[msgNum]).getFrom()[0]).getAddress();
                        if(from == null)
                            from = "";
                        String personal = ((InternetAddress)((MimeMessage)msgs[msgNum]).getFrom()[0]).getPersonal();
                        if(personal == null)
                            personal = "";
                        String fromaddr = (new StringBuilder(String.valueOf(personal))).append("\u0448").append("<").append(from).append(">").toString();
                        String subject = ((MimeMessage)msgs[msgNum]).getSubject();
                        String chaos = getMailAddress("BCC", (MimeMessage)msgs[msgNum]);
                        String date = getSentDate((MimeMessage)msgs[msgNum]);
                        boolean fujian = isContainAttach((MimeMessage)msgs[msgNum]);
                        boolean hz = getReplySign((MimeMessage)msgs[msgNum]);
                        String attachname = AttachMentName((MimeMessage)msgs[msgNum], null);
                        getMailContent((MimeMessage)msgs[msgNum], bodytext);
                        String neitongtxt = getBodyText("txt", bodytext);
                        String neitonghtml = getBodyText("html", bodytext);
                        boolean attachresult = false;
                        if(fujian)
                        {
                             URL = setFinallyPath(path, mailid, date);
                            setAttachPath(URL);
                            attachresult = saveAttachMent((MimeMessage)msgs[msgNum]);
                        }
                        MailVO vo = new MailVO();
                        vo.setMailid(mailid);
                        vo.setMailNum(mailNum);
                        vo.setTo(sjr);
                        vo.setFrom(fromaddr);
                        vo.setSubject(subject);
                        vo.setChaosong(chaos);
                        vo.setDate(date);
                        vo.setAccessory(fujian);
                        vo.setHuizhi(hz);
                        vo.setAttachname(attachname);
                        vo.setContenttxt(neitongtxt);
                        vo.setContenthtml(neitonghtml);
                        vo.setAttachresult(attachresult);
                        list.add(vo);
                    }
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }finally{
            if(store != null)
				try {
					if(folder != null){
						folder.close(false);
					}
					if(store!=null){
						store.close();
					}
				} catch (MessagingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        }
        return list;
    }

    public static boolean download(String popServer, String popUser, String popPassword, int mailid, String path, String filename)
    {
        Store store;
        Folder folder;
        boolean result;
        store = null;
        folder = null;
        result = false;
        try
        {
            java.util.Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props, null);
            store = session.getStore("pop3");
            store.connect(popServer, popUser, popPassword);
            folder = store.getDefaultFolder();
            if(folder == null)
                throw new Exception("\u6CA1\u6709\u6587\u4EF6\u5939\uFF01");
            folder = folder.getFolder("INBOX");
            if(folder == null)
                throw new Exception("\u6CA1\u6709POP3\u6536\u4EF6\u7BB1");
            folder.open(1);
            MimeMessage message = (MimeMessage)folder.getMessage(mailid);
            boolean fujian = isContainAttach(message);
            if(fujian)
            {
                setAttachPath(path);
                result = savetheAttachMent(message, filename);
            } else
            {
                System.out.println("\u672C\u90AE\u4EF6\u65E0\u9644\u4EF6\u53EF\u4E0B\u8F7D\uFF01");
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }finally{
            if(store != null)
				try {
					if(folder != null){
						folder.close(false);
					}
					if(store!=null){
						store.close();
					}
				} catch (MessagingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        }
        return result;
    }

    
    
    
    public static boolean download(String popServer, String popUser, String popPassword, int mailid, String path)
    {
        Store store;
        Folder folder;
        boolean result;
        store = null;
        folder = null;
        result = false;
        try
        {
            java.util.Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props, null);
            store = session.getStore("pop3");
            store.connect(popServer, popUser, popPassword);
            folder = store.getDefaultFolder();
            if(folder == null)
                throw new Exception("\u6CA1\u6709\u6587\u4EF6\u5939\uFF01");
            folder = folder.getFolder("INBOX");
            if(folder == null)
                throw new Exception("\u6CA1\u6709POP3\u6536\u4EF6\u7BB1");
            folder.open(1);
            MimeMessage message = (MimeMessage)folder.getMessage(mailid);
            boolean fujian = isContainAttach(message);
            if(fujian)
            {
                setAttachPath(path);
                result = saveAttachMent(message);
            } else
            {
                System.out.println("\u672C\u90AE\u4EF6\u65E0\u9644\u4EF6\u53EF\u4E0B\u8F7D\uFF01");
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }finally{
            if(store != null)
				try {
					if(folder != null){
						folder.close(false);
					}
					if(store!=null){
						store.close();
					}
				} catch (MessagingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        }
        return result;
    }

    public static MailVO mailDetail(String popServer, String popUser, String popPassword, String mailid)
    {
        Store store;
        Folder folder;
        MailVO vo;
        store = null;
        folder = null;
        vo = new MailVO();
        try
        {
            java.util.Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props, null);
            store = session.getStore("pop3");
            store.connect(popServer, popUser, popPassword);
            folder = store.getDefaultFolder();
            if(folder == null)
                throw new Exception("\u6CA1\u6709\u6587\u4EF6\u5939\uFF01");
            folder = folder.getFolder("INBOX");
            if(folder == null)
                throw new Exception("\u6CA1\u6709POP3\u6536\u4EF6\u7BB1");
            folder.open(1);
            MimeMessage msg[] = (MimeMessage[])folder.getMessages();
            for(int i = 0; i < msg.length; i++)
            {
                StringBuffer bodytext = new StringBuffer();
                if(msg[i].getMessageID().equals(mailid))
                {
                    MimeMessage message = msg[i];
                    Part messagePart = message;
                    int mailNum = message.getMessageNumber();
                    String sjr = getMailAddress("to", message);
                    String from = ((InternetAddress)message.getFrom()[0]).getAddress();
                    if(from == null)
                        from = "";
                    String personal = ((InternetAddress)message.getFrom()[0]).getPersonal();
                    if(personal == null)
                        personal = "";
                    String fromaddr = (new StringBuilder(String.valueOf(personal))).append("\u0448").append("<").append(from).append(">").toString();
                    String subject = message.getSubject();
                    String chaos = getMailAddress("BCC", message);
                    String date = getSentDate(message);
                    boolean fujian = isContainAttach(message);
                    boolean hz = getReplySign(message);
                    String attachname = AttachMentName(messagePart, null);
                    getMailContent(messagePart, bodytext);
                    String neitongtxt = getBodyText("txt", bodytext);
                    String neitonghtml = getBodyText("html", bodytext);
                    vo.setMailid(mailid);
                    vo.setMailNum(mailNum);
                    vo.setTo(sjr);
                    vo.setFrom(fromaddr);
                    vo.setSubject(subject);
                    vo.setChaosong(chaos);
                    vo.setDate(date);
                    vo.setAccessory(fujian);
                    vo.setHuizhi(hz);
                    vo.setAttachname(attachname);
                    vo.setContenthtml(neitonghtml);
                    vo.setContenttxt(neitongtxt);
                }
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }finally{
            if(store != null)
				try {
					if(folder != null){
						folder.close(false);
					}
					if(store!=null){
						store.close();
					}
				} catch (MessagingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        }
        return vo;
    }

    public static void deletemail(String popServer, String popUser, String popPassword, String mailid[])
    {
        Store store;
        Folder folder;
        store = null;
        folder = null;
        try
        {
            java.util.Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props, null);
            store = session.getStore("pop3");
            store.connect(popServer, popUser, popPassword);
            folder = store.getDefaultFolder();
            if(folder == null)
                throw new Exception("\u6CA1\u6709\u6587\u4EF6\u5939\uFF01");
            folder = folder.getFolder("INBOX");
            if(folder == null)
                throw new Exception("\u6CA1\u6709POP3\u6536\u4EF6\u7BB1");
            folder.open(2);
            for(int i = 0; i < mailid.length; i++)
            {
                int id = 0;
                Message msgs[] = folder.getMessages();
                for(int j = 0; j < msgs.length; j++)
                    if(((MimeMessage)msgs[j]).getMessageID().equals(mailid[i]))
                        id = msgs[j].getMessageNumber();

                if(id != 0)
                {
                    Message message = folder.getMessage(id);
                    message.setFlag(javax.mail.Flags.Flag.DELETED, true);
                    if(message.isSet(javax.mail.Flags.Flag.DELETED))
                        System.out.println((new StringBuilder("\u7B2C")).append(id).append("\u5C01\u90AE\u4EF6\u5220\u9664\u6210\u529F\uFF01").toString());
                }
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }finally{
            if(store != null)
				try {
					if(folder != null){
						folder.close(false);
					}
					if(store!=null){
						store.close();
					}
				} catch (MessagingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        }
    }

    public static void receive(String popServer, String popUser, String popPassword)
    {
        Store store;
        Folder folder;
        store = null;
        folder = null;
        try
        {
            java.util.Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props, null);
            store = session.getStore("pop3");
            store.connect(popServer, popUser, popPassword);
            folder = store.getDefaultFolder();
            folder = folder.getFolder("INBOX");
            folder.open(2);
            
            Message msgs[] = folder.getMessages();
            int Deletemail = folder.getDeletedMessageCount();
            int newmail = folder.getNewMessageCount();
            int unread = folder.getUnreadMessageCount();
            for(int msgNum = 0; msgNum < msgs.length; msgNum++)
            {
                if(msgs[msgNum].isSet(javax.mail.Flags.Flag.DELETED))
                {
                    System.out.println("");
                } else
                {
                    printMessage((MimeMessage)msgs[msgNum]);
                }
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }finally{
            if(store != null)
				try {
					if(folder != null){
						folder.close(false);
					}
					if(store!=null){
						store.close();
					}
				} catch (MessagingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        }
        
    }

    public static void printMessage(MimeMessage message)
    {
        try
        {
            String from = ((InternetAddress)message.getFrom()[0]).getPersonal();
            if(from == null)
                from = ((InternetAddress)message.getFrom()[0]).getAddress();
            String subject = message.getSubject();
            Part messagePart = message;
            Object content = messagePart.getContent();
            String sjr = getMailAddress("to", message);
            String chaos = getMailAddress("BCC", message);
            String date = getSentDate(message);
            String mailid = getMessageId(message);
            boolean hz = getReplySign(message);
            boolean sfyd = isNew(message);
            boolean fujian = isContainAttach(message);
            if(fujian)
            {
                messagePart = ((Multipart)content).getBodyPart(0);
                saveAttachMent(message);
            } else
            {
            }
            StringBuffer bodytext = new StringBuffer();
            getMailContent(messagePart, bodytext);
            String neitong = getBodyText(null, bodytext);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public static void getMailContent(Part part, StringBuffer bodytext)
        throws Exception
    {
        String contenttype = part.getContentType();
        int nameindex = contenttype.indexOf("name");
        boolean conname = false;
        if(nameindex != -1)
            conname = true;
        if(part.isMimeType("text/plain") && !conname)
            bodytext.append((String)part.getContent()).append("\u0448");
        else
        if(part.isMimeType("text/html") && !conname)
            bodytext.append((String)part.getContent()).append("\u0448");
        else
        if(part.isMimeType("multipart/*"))
        {
            Multipart multipart = (Multipart)part.getContent();
            int counts = multipart.getCount();
            for(int i = 0; i < counts; i++)
                getMailContent(((Part) (multipart.getBodyPart(i))), bodytext);

        } else
        if(part.isMimeType("message/rfc822"))
            getMailContent((Part)part.getContent(), bodytext);
    }

    public static String getBodyText(String type, StringBuffer bodytext)
    {
        String content[] = bodytext.toString().split("\u0448");
        String txtcontent = content[0];
        String htmlcontent = "";
        if(!bodytext.toString().endsWith("\u0448"))
            htmlcontent = content[1];
        if(type == null || type.equals(""))
            return bodytext.toString();
        if(type.equals("txt"))
            return txtcontent;
        if(type.equals("html"))
            return htmlcontent;
        else
            return bodytext.toString();
    }

    public static boolean isNew(MimeMessage mimeMessage)
        throws MessagingException
    {
        boolean isnew = false;
        Flags flags = mimeMessage.getFlags();
        javax.mail.Flags.Flag flag[] = flags.getSystemFlags();
        for(int i = 0; i < flag.length; i++)
        {
            if(flag[i] != javax.mail.Flags.Flag.SEEN)
                continue;
            isnew = true;
            break;
        }

        return isnew;
    }

    public static boolean getReplySign(MimeMessage mimeMessage)
        throws MessagingException
    {
        boolean replysign = false;
        String needreply[] = mimeMessage.getHeader("Disposition-Notification-To");
        if(needreply != null)
            replysign = true;
        return replysign;
    }

    public static String getMessageId(MimeMessage mimeMessage)
        throws MessagingException
    {
        return mimeMessage.getMessageID();
    }

    public static String getSentDate(MimeMessage mimeMessage)
        throws Exception
    {
        java.util.Date sentdate = mimeMessage.getSentDate();
        SimpleDateFormat format = new SimpleDateFormat(dateformat);
        return format.format(sentdate);
    }

    public static String getMailAddress(String type, MimeMessage mimeMessage)
        throws Exception
    {
        String mailaddr = "";
        String addtype = type.toUpperCase();
        InternetAddress address[] = (InternetAddress[])null;
        if(addtype.equals("TO") || addtype.equals("CC") || addtype.equals("BCC"))
        {
            if(addtype.equals("TO"))
                address = (InternetAddress[])mimeMessage.getRecipients(javax.mail.Message.RecipientType.TO);
            else
            if(addtype.equals("CC"))
                address = (InternetAddress[])mimeMessage.getRecipients(javax.mail.Message.RecipientType.CC);
            else
                address = (InternetAddress[])mimeMessage.getRecipients(javax.mail.Message.RecipientType.BCC);
            if(address != null)
            {
                for(int i = 0; i < address.length; i++)
                {
                    String email = address[i].getAddress();
                    if(email == null)
                        email = "";
                    else
                        email = MimeUtility.decodeText(email);
                    String personal = address[i].getPersonal();
                    if(personal == null)
                        personal = "";
                    else
                        personal = MimeUtility.decodeText(personal);
                    String compositeto = (new StringBuilder(String.valueOf(personal))).append("<").append(email).append(">").toString();
                    mailaddr = (new StringBuilder(String.valueOf(mailaddr))).append(",").append(compositeto).toString();
                }

                mailaddr = mailaddr.substring(1);
            }
        } else
        {
            throw new Exception("Error emailaddr type!");
        }
        return mailaddr;
    }

    public static boolean isContainAttach(Part part)
        throws Exception
    {
        boolean attachflag = false;
        String contentType = part.getContentType();
        if(part.isMimeType("multipart/*"))
        {
            Multipart mp = (Multipart)part.getContent();
            for(int i = 0; i < mp.getCount(); i++)
            {
                BodyPart mpart = mp.getBodyPart(i);
                String disposition = mpart.getDisposition();
                if(disposition != null && (disposition.equals("attachment") || disposition.equals("inline")))
                    attachflag = true;
                else
                if(mpart.isMimeType("multipart/*"))
                {
                    attachflag = isContainAttach(((Part) (mpart)));
                } else
                {
                    String contype = mpart.getContentType();
                    if(contype.toLowerCase().indexOf("application") != -1)
                        attachflag = true;
                    if(contype.toLowerCase().indexOf("name") != -1)
                        attachflag = true;
                }
            }

        } else
        if(part.isMimeType("message/rfc822"))
            attachflag = isContainAttach((Part)part.getContent());
        return attachflag;
    }

    public static String AttachMentName(Part part, String fileName)
        throws Exception
    {
        if(fileName == null)
            fileName = "";
        String fileName1 = "";
        if(part.isMimeType("multipart/*"))
        {
            Multipart mp = (Multipart)part.getContent();
            for(int i = 1; i < mp.getCount(); i++)
            {
                BodyPart mpart = mp.getBodyPart(i);
                String disposition = mpart.getDisposition();
                if(disposition != null && (disposition.equals("attachment") || disposition.equals("inline")))
                {
                    fileName1 = mpart.getFileName();
                    if(fileName1.toLowerCase().indexOf("gbk") != -1 || fileName1.toLowerCase().indexOf("gb2312") != -1)
                        fileName1 = MimeUtility.decodeText(fileName1);
                } else
                if(mpart.isMimeType("multipart/*"))
                {
                    AttachMentName(((Part) (mpart)), fileName);
                } else
                {
                    fileName1 = mpart.getFileName();
                    if(fileName1 != null && (fileName1.toLowerCase().indexOf("gbk") != -1 || fileName1.toLowerCase().indexOf("GB2312") != -1))
                        fileName1 = MimeUtility.decodeText(fileName1);
                }
                if(fileName.equals(""))
                    fileName = (new StringBuilder(String.valueOf(fileName))).append(fileName1).toString();
                else
                    fileName = (new StringBuilder(String.valueOf(fileName))).append("\u0448").append(fileName1).toString();
            }

        } else
        if(part.isMimeType("message/rfc822"))
            AttachMentName((Part)part.getContent(), fileName);
        return fileName;
    }

    public static boolean savetheAttachMent(Part part, String filename)
        throws Exception
    {
        String fileName = "";
        boolean result = false;
        if(part.isMimeType("multipart/*"))
        {
            Multipart mp = (Multipart)part.getContent();
            for(int i = 0; i < mp.getCount(); i++)
            {
                BodyPart mpart = mp.getBodyPart(i);
                String disposition = mpart.getDisposition();
                if(disposition != null && (disposition.equals("attachment") || disposition.equals("inline")))
                {
                    fileName = mpart.getFileName();
                    if(fileName.toLowerCase().indexOf("gbk") != -1 || fileName.toLowerCase().indexOf("gb2312") != -1)
                        fileName = MimeUtility.decodeText(fileName);
                    if(fileName.equals(filename))
                    {
                        saveFile(fileName, mpart.getInputStream());
                        result = true;
                    }
                } else
                if(mpart.isMimeType("multipart/*"))
                {
                    saveAttachMent(mpart);
                } else
                {
                    fileName = mpart.getFileName();
                    if(fileName != null && (fileName.toLowerCase().indexOf("gbk") != -1 || fileName.toLowerCase().indexOf("GB2312") != -1))
                    {
                        fileName = MimeUtility.decodeText(fileName);
                        if(fileName.equals(filename))
                        {
                            saveFile(fileName, mpart.getInputStream());
                            result = true;
                        }
                    }
                }
            }

        } else
        if(part.isMimeType("message/rfc822"))
            saveAttachMent((Part)part.getContent());
        return result;
    }

    public static boolean saveAttachMent(Part part)
        throws Exception
    {
        String fileName = "";
        boolean result = false;
        if(part.isMimeType("multipart/*"))
        {
            Multipart mp = (Multipart)part.getContent();
            for(int i = 0; i < mp.getCount(); i++)
            {
                BodyPart mpart = mp.getBodyPart(i);
                String disposition = mpart.getDisposition();
                if(disposition != null && (disposition.equals("attachment") || disposition.equals("inline")))
                {
                    fileName = mpart.getFileName();
                    if(fileName.toLowerCase().indexOf("gbk") != -1 || fileName.toLowerCase().indexOf("gb2312") != -1)
                        fileName = MimeUtility.decodeText(fileName);
                    saveFile(fileName, mpart.getInputStream());
                    result = true;
                } else
                if(mpart.isMimeType("multipart/*"))
                {
                    saveAttachMent(((Part) (mpart)));
                } else
                {
                    fileName = mpart.getFileName();
                    if(fileName != null && (fileName.toLowerCase().indexOf("gbk") != -1 || fileName.toLowerCase().indexOf("GB2312") != -1))
                    {
                        fileName = MimeUtility.decodeText(fileName);
                        saveFile(fileName, mpart.getInputStream());
                        result = true;
                    }
                }
            }

        } else
        if(part.isMimeType("message/rfc822"))
            saveAttachMent((Part)part.getContent());
        return result;
    }

    public static String checkFileName(String url, String fileName)
    {
        String FileName = "";
        String FILENAME = fileName;
        String geshi = "";
        File file = new File(url);
        File codeFile[] = file.listFiles();
        for(int i = 0; i < codeFile.length; i++)
        {
            FileName = codeFile[i].getName();
            if(FileName.equals(fileName))
            {
                p++;
                int j = FileName.lastIndexOf(".");
                geshi = fileName.substring(j + 1, fileName.length());
                FILENAME = (new StringBuilder(String.valueOf(fileName.substring(0, j)))).append(" (").append(String.valueOf(p + 1)).append(")").append(".").append(geshi).toString();
            }
        }

        return FILENAME;
    }

    private static void saveFile(String fileName, InputStream in) throws Exception
    {
        File storefile;
        BufferedOutputStream bos;
        BufferedInputStream bis;
        String osName = System.getProperty("os.name");
        String storedir = getAttachPath();
        String separator = "";
        if(osName == null)
            osName = "";
        
        bos = null;
        bis = null;
        
        if(osName.toLowerCase().indexOf("win") == -1)
        {
	        separator = "\\";
	        if(storedir != null && !storedir.equals("")){
	            separator = "/";
	        }
	        pathCheck(pathProcess(storedir));
	        String FILENAME = "";
	        try
	        {
	            FILENAME = checkFileName((new StringBuilder(String.valueOf(storedir))).append(separator).toString(), fileName);
	        }
	        catch(Exception e)
	        {
	            FILENAME = fileName;
	        }
	        storefile = new File((new StringBuilder(String.valueOf(storedir))).append(separator).append(FILENAME).toString());
	        
	        try{
		        bos = new BufferedOutputStream(new FileOutputStream(storefile));
	            bis = new BufferedInputStream(in);
	            int c;
	            while((c = bis.read()) != -1) 
	            {
	                bos.write(c);
	                bos.flush();
	            }
	        }catch(Exception exception)
	        {
	            exception.printStackTrace();
	            throw exception;
	        }finally{
	        	bos.close();
	            bis.close();
	        }
        }
        
    }

    
    
    public static String getAttachPath()
    {
        return saveAttachPath;
    }

    public static void setAttachPath(String attachpath)
    {
        saveAttachPath = attachpath;
    }

    public static String setFinallyPath(String path, String mailid, String date)
    {
        String URL = "";
        StringBuffer sb = new StringBuffer();
        String year = date.substring(0, 2);
        String month = date.substring(3, 5);
        String day = date.substring(6, 8);
        String MailId = mailid.substring(1, mailid.length() - 1);
        sb.append(path).append("/").append(year).append(month).append("/").append(year).append(month).append(day).append("/").append(MailId);
        URL = sb.toString();
        return URL;
    }

    public void setDateFormat(String format)
        throws Exception
    {
        dateformat = format;
    }
    
    public static boolean pathCheck(String path)
    {
        try
        {
            if(!(new File(path)).isDirectory())
                (new File(path)).mkdirs();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return true;
        }
        return true;
    }

    
    
    public static String pathProcess(String path)
    {
        if(System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") == -1 && !path.startsWith("/"))
            path = (new StringBuilder("/")).append(path).toString();
        return path;
    }
   

}